package com.cat.gridChart;

/**
 *   @description https://leetcode.cn/problems/detect-cycles-in-2d-grid/description/
 *   @author 曲大人的喵
 *   @create 2025/9/7 16:02
 *   @since JDK17
 */

public class Solution10 {
    int n, m;
    int[][] d = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    boolean[][] vis;
    char[][] g;

    boolean dfs(int x, int y, int fx, int fy) {
        boolean flag = false;
        vis[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int nx = x + d[i][0], ny = y + d[i][1];
            if (nx == -1 || nx == n || ny == -1 || ny == m) {
                continue;
            }
            if (g[x][y] == g[nx][ny] && (nx != fx || ny != fy)) {
                if (vis[nx][ny]) {
                    flag = true;
                    break;
                }
                flag |= dfs(nx, ny, x, y);
            }
        }

        return flag;
    }

    public boolean containsCycle(char[][] grid) {
        g = grid;
        n = grid.length;
        m = grid[0].length;
        vis = new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!vis[i][j] && dfs(i, j, -1, -1)) {
                    return true;
                }
            }
        }
        return false;
    }
}